package com.hepinghospital.user.ui.activity.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.graphic.graphicSelect.GraphicSelectActivity;
import com.hepinghospital.user.ui.widget.CustomPopWindow;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.DicResponse;
import com.rest.response.Doctor;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilString;


/**
 * 图文问诊医生
 * Created by lbj on 2021/8/23 11:50
 */

public class BookDoctor2Activity extends BaseActivity {

    @BindView(R.id.refreshLayout)
    public RefreshLayout refreshLayout;
    @BindView(R.id.doctor_recyclerView)
    public RecyclerView doctor_recyclerView;
    @BindView(R.id.btn_zhichen)
    TextView btn_zhichen;
    @BindView(R.id.btn_keshi)
    TextView btn_keshi;
    @BindView(R.id.tv_chufang)
    TextView tvChufang;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_search)
    public ImageView btnSearch;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.icon1)
    ImageView icon1;
    @BindView(R.id.icon2)
    ImageView icon2;
    @BindView(R.id.icon3)
    ImageView icon3;
    private CustomPopWindow mPopWindow;
    List<DicResponse> list = new ArrayList<>();

    public List<Doctor> doctorList = new ArrayList<>();
    public DoctorAdapter doctorAdapter;
    public AddMedicineAdapter adapter;
    public int type;
    public int current = 1;
    public String content = "", codeType = "", deptId = "0", code = "", checkDetailId;
    private String isPrescription = "";

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_book_docot2;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        doctor_recyclerView.setLayoutManager(manager);
        doctorAdapter = new DoctorAdapter();
        doctor_recyclerView.setAdapter(doctorAdapter);
        doctor_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(mContext, 16);
            }
        });

        refreshLayout.setOnRefreshListener(refreshlayout -> {
            current = 1;
            getDoctorList(deptId, content, isPrescription);
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            current++;
            getDoctorList(deptId, content, isPrescription);
        });
    }

    @Override
    protected void initData() {
        type = getIntent().getIntExtra("type", -1);
        checkDetailId = getIntent().getStringExtra("checkDetailId");
        getDoctorList(deptId, content, isPrescription);
    }

    @OnClick(R.id.btn_search)
    void btn_search() {
        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        bundle.putString("checkDetailId", checkDetailId);
        startActivity(SearchDoctorActivity.class, bundle);
    }

    public void inBindViewHolder(DoctorAdapter.Holder holder, final int position){
        holder.itemView.setOnClickListener(v -> {
            startGraphicSelectActivity(position);
        });
        holder.tv_level.setText(doctorList.get(position).jobTitleName);
        holder.tv_skill.setText("擅长:" + doctorList.get(position).docGoodAtNames);

        holder.tv_name.setText(doctorList.get(position).docName);
        if (!UtilString.isEmpty(doctorList.get(position).num)) {
            holder.tv_turnNum.setVisibility(View.VISIBLE);
            holder.tv_turnNum.setText("咨询数 " + doctorList.get(position).num);
        } else {
            holder.tv_turnNum.setVisibility(View.GONE);
        }
        ImageLoaderHelper.getInstance().GlideCircleImageLoader(BookDoctor2Activity.this, doctorList.get(position).thumbnailUrl, holder.img_head);
        if (doctorList.get(position).isPrescription == 1) {
            holder.tv_recipel.setText("处方");
            holder.tv_recipel.setTextColor(Color.parseColor("#ff209187"));
        } else {
            holder.tv_recipel.setText("非处方");
            holder.tv_recipel.setTextColor(Color.parseColor("#ffd5d5d5"));
        }
        if (!UtilString.isEmpty(doctorList.get(position).deptName)) {
            holder.tv_deptName.setText(doctorList.get(position).deptName);
        } else {
            holder.tv_deptName.setVisibility(View.GONE);
        }

        if ("0".equals(doctorList.get(position).isRecommend)) {
            holder.tvRecommend.setVisibility(View.GONE);
        } else {
            holder.tvRecommend.setVisibility(View.VISIBLE);
        }
        if (!UtilString.isEmpty(doctorList.get(position).score)) {
            holder.tv_star.setText(doctorList.get(position).score);
//            holder.ratingBar.setRating(Float.parseFloat(doctorList.get(position).score));
        }else{
            holder.tv_star.setText(doctorList.get(position).getEvaluate());
//            holder.ratingBar.setRating(Float.parseFloat(doctorList.get(position).getEvaluate()));
        }

    }


    private void startGraphicSelectActivity(final int position){
        Bundle bundle = new Bundle();
        bundle.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
        bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_0);
        bundle.putString("checkDetailId", checkDetailId);
        startActivity(GraphicSelectActivity.class, bundle);
    }

    public class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(BookDoctor2Activity.this).inflate(R.layout.item_book_doctor_online, parent, false));
            return myHolder;
        }



        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            inBindViewHolder(holder,position);
        }

        @Override
        public int getItemCount() {
            return doctorList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {

            public TextView tv_name, tv_level, tv_recipel, tv_deptName, tv_skill, tv_star, tv_turnNum,tvRecommend;
            public ImageView img_head;
            public RatingBar ratingBar;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_level = itemView.findViewById(R.id.tv_level);
                tv_recipel = itemView.findViewById(R.id.tv_recipel);
                tv_deptName = itemView.findViewById(R.id.tv_deptName);
                tv_skill = itemView.findViewById(R.id.tv_skill);
                tv_star = itemView.findViewById(R.id.tv_star);
                img_head = itemView.findViewById(R.id.img_head);
                ratingBar = itemView.findViewById(R.id.ratingBar);
                tv_turnNum = itemView.findViewById(R.id.tv_turn_num);
                tvRecommend = itemView.findViewById(R.id.iv_recommend);
            }
        }
    }

    public void getDoctorList(String deptId, String content, String isPrescription) {
        RestProxy.getInstance().getPhotoDoctorList(deptId, content, code, type + "", current + "", "10", isPrescription, new BaseObserver<CloudDoctorResponse>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(BookDoctor2Activity.this, e);
                if (current == 1) {
                    refreshLayout.finishRefresh(true);
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onSuccess(CloudDoctorResponse doctorResponse) {
                Log.e("图文咨询医生====", doctorResponse.records.size() + "");
                if (current == 1) {
                    doctorList.clear();
                    doctorList.addAll(doctorResponse.records);
                    refreshLayout.finishRefresh(true);
                } else {
                    if (doctorResponse.records.size() == 0) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                        return;
                    }
                    doctorList.addAll(doctorResponse.records);
                    refreshLayout.finishLoadMore();
                }
                doctorAdapter.notifyDataSetChanged();
            }
        });
    }


    @OnClick(R.id.btn_keshi)
    void btn_keshi() {
        icon1.setImageResource(R.mipmap.icon_pop);
        icon3.setImageResource(R.mipmap.icon_pop);
        icon2.setImageResource(R.mipmap.icon_down);
        btn_zhichen.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        btn_keshi.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        showPopListView(btn_keshi, 0);
    }

    @OnClick(R.id.btn_zhichen)
    void btn_zhichen() {
        icon1.setImageResource(R.mipmap.icon_pop);
        icon3.setImageResource(R.mipmap.icon_down);
        icon2.setImageResource(R.mipmap.icon_pop);
        btn_zhichen.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        btn_keshi.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        showPopListView(btn_zhichen, 1);

    }

    @OnClick(R.id.tv_chufang)
    void tv_chufang() {
        icon1.setImageResource(R.mipmap.icon_down);
        icon3.setImageResource(R.mipmap.icon_pop);
        icon2.setImageResource(R.mipmap.icon_pop);
        btn_zhichen.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        btn_keshi.setTextColor(ContextCompat.getColor(this, R.color.commonGrey));
        tvChufang.setTextColor(ContextCompat.getColor(this, R.color.mainBlue));
        showPopListView(tvChufang, 2);
    }

    private void showPopListView(View view, int type) {
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(BookDoctor2Activity.this).inflate(R.layout.pop_window, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(BookDoctor2Activity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new AddMedicineAdapter(this, type);
        recyclerView.setAdapter(adapter);
//        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
//            @Override
//            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
//                super.onDraw(c, parent, state);
//            }
//
//            @Override
//            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//                super.getItemOffsets(outRect, view, parent, state);
//                outRect.bottom = DpUtil.dip2px(activity, 1);
//            }
//        });
        if (type == 1) {
            //职称信息
            getDictList();
        } else if (type == 0) {
            //按照科室
            getDepartmentList();
        } else {
            list.clear();
            list.add(new DicResponse("全部", "0"));
            list.add(new DicResponse("处方", "1"));
            list.add(new DicResponse("非处方", "2"));
            adapter.notifyDataSetChanged();
        }

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(BookDoctor2Activity.this)
                .setView(contentView)
                .setTouchable(true)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DpUtil.dip2px(BookDoctor2Activity.this, 300)) // 显示大小
                .create()
                .showAsDropDown(view, 0, 0, Gravity.CENTER);
    }


    class AddMedicineAdapter extends RecyclerView.Adapter<AddMedicineAdapter.Holder> {

        int type;
        private Context context;

        AddMedicineAdapter(Context context, int type) {
            this.context = context;
            this.type = type;
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(BookDoctor2Activity.this).inflate(R.layout.item_textview, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (type == 0) {
                    //按照科室查询
                    if (position == 0) {
                        content = "";
                        deptId = "0";
                        btn_keshi.setText("科室");
                    } else {
                        content = list.get(position).name;
                        btn_keshi.setText(list.get(position).name);
                        deptId = list.get(position).id;
                    }
                    btn_keshi.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                    getDoctorList(deptId, content, isPrescription);
                    mPopWindow.dissmiss();
                } else if (type == 1) {
                    //点击的职称查询
                    if (position == 0) {
                        code = "";
                        btn_zhichen.setText("职称");
                    } else {
                        code = list.get(position).code;
                        btn_zhichen.setText(list.get(position).name);
                    }
                    btn_zhichen.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                    getDoctorList(deptId, content, isPrescription);
                    mPopWindow.dissmiss();
                } else {
                    codeType = list.get(position).code;
                    if ("1".equals(codeType)) {
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                        tvChufang.setText("处方");
                        isPrescription = "1";
                    } else if ("2".equals(codeType)) {
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.mainBlue));
                        tvChufang.setText("非处方");
                        isPrescription = "0";
                    } else {
                        tvChufang.setText("处方权限");
                        tvChufang.setTextColor(ContextCompat.getColor(context, R.color.commonGrey));
                        isPrescription = "";
                    }
                    getDoctorList(deptId, content, isPrescription);
                    mPopWindow.dissmiss();
                }
            });
            holder.tv_name.setText(list.get(position).name);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.text);
            }
        }
    }

    private void getDictList() {
        RestProxy.getInstance().getDicList(new BaseObserver<List<DicResponse>>() {

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(BookDoctor2Activity.this, e);

            }

            @Override
            public void onSuccess(List<DicResponse> result) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(result);
                adapter.notifyDataSetChanged();
            }
        });
    }


    private void getDepartmentList() {
        RestProxy.getInstance().getDepartment2List(new Observer<List<DicResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<DicResponse> dicResponses) {
                list.clear();
                list.add(new DicResponse("全部", ""));
                list.addAll(dicResponses);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishRefresh(false);
                ToastUtil.onError(BookDoctor2Activity.this, e);

            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }
}
